package user

import (
	"context"
	"go.uber.org/zap"
	"navi-mumbai/app/api/business/internal/svc"
	"navi-mumbai/app/api/business/internal/types"
	"navi-mumbai/app/rpc/usercenter/pb"
	pbWallet "navi-mumbai/app/rpc/wallet/pb"
	"navi-mumbai/common/ctxdata"
	"navi-mumbai/common/key/walletkey"
	"navi-mumbai/common/xerr"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserReceiveRewardLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserReceiveRewardLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserReceiveRewardLogic {
	return &UserReceiveRewardLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserReceiveRewardLogic) UserReceiveReward(req *types.UserReceiveRewardReq) (resp *types.UserReceiveRewardResp, err error) {
	uid := ctxdata.GetUidFromCtx(l.ctx)
	if uid != req.Uid {
		return nil, xerr.NewGrpcErrCodeMsg(xerr.AuthFail, "no privilege")
	}

	// 查询礼物 校验礼物 更新礼物状态
	var in pb.ReceiveUserRewardReq
	in.Uid = req.Uid
	in.Id = req.Id
	var rsp *pb.ReceiveUserRewardResp
	rsp, err = l.svcCtx.UcUserRpc.ReceiveUserReward(l.ctx, &in)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return
	}
	// 领取礼物
	switch rsp.RewardType {
	case walletkey.UsingCurrencyType: //userkey.RewardTypeGold:
		var in2 pbWallet.DepositDirectReq
		in2.Uid = req.Uid
		in2.MoneyAmount = rsp.RewardAmount
		in2.MoneyType = walletkey.UsingCurrencyType
		in2.PayChannelId = walletkey.PayChannelIdSystem
		in2.CurrencyAmount = "0"
		var rsp2 *pbWallet.DepositDirectResp
		rsp2, err = l.svcCtx.WalletSysRpc.DepositDirect(l.ctx, &in2)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return
		}
		resp = &types.UserReceiveRewardResp{
			MoneyType: rsp2.MoneyType,
			Balance:   rsp2.Balance,
		}
	default:
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, "reward type error")
	}

	return
}
